package com.swq.java.code.chapter20.code16;

import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AudioPlayer extends JApplet {
    private AudioClip[] sounds;
    private AudioClip currentSound;
    private JButton playSound, loopSound, stopSound;
    private JComboBox<String> chooseSound;

    public AudioPlayer() {
        String choices[] = {"happyface.wav", "moonriver.wav", "horse.mid", "eagle.wav"};

        setLayout(new FlowLayout());
        chooseSound = new JComboBox<String>(choices);
        chooseSound.addItemListener(
                new ItemListener() {
                    public void itemStateChanged(ItemEvent e) {
                        currentSound.stop();
                        currentSound = sounds[chooseSound.getSelectedIndex()];
                    }
                });
        add(chooseSound);

        ButtonHandler handler = new ButtonHandler();
        playSound = new JButton("Play");
        playSound.addActionListener(handler);
        add(playSound);
        loopSound = new JButton("Loop");
        loopSound.addActionListener(handler);
        add(loopSound);
        stopSound = new JButton("Stop");
        stopSound.addActionListener(handler);
        add(stopSound);

        sounds = new AudioClip[choices.length];
        for (int i = 0; i < choices.length; i++)
            sounds[i] = newAudioClip(getClass().getClassLoader().getResource(choices[i]));

        currentSound = sounds[0];
    }

    private class ButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == playSound)
                currentSound.play();
            else if (e.getSource() == loopSound)
                currentSound.loop();
            else if (e.getSource() == stopSound)
                currentSound.stop();
        }
    }

    public static void main(String args[]) {
        JFrame gui = new JFrame("音乐播放器");
        AudioPlayer player = new AudioPlayer();
        gui.setContentPane(player);
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(400, 100);
        gui.setVisible(true);
    }
}